package com.mairuide.phone.meet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mairuide._frame.base.BaseController;
import com.mairuide._frame.base.ModuleCode;
import com.mairuide._frame.utils.StringUtils;
import com.mairuide.bill.utils.ExcelUtil;

/**
 * 碰面分析
 * @author mh
 *
 */
@Controller
@RequestMapping("/meet")
public class MeetAnalysisController extends BaseController {
	
	
	@Resource
	private MeetAnalysisService meetAnalysisService;
	
	/**
	 * 碰面分析init
	 * @param model
	 * @param eocap
	 * @return
	 */
	@ModuleCode(pValue = "meet", value = "meetMC")
	@RequestMapping(value = "/meetAnalysisInit", method = RequestMethod.GET)
	public Object init(ModelMap model,MeetAnalysisParams meetp) {
		model.addAttribute("eca",null);
		model.addAttribute("meetp",meetp);
		model.addAttribute("phones", null);
		return "/phone/meet/meetanalysis";
	}
	
	/**
	 * 碰面分析
	 * @param model
	 * @param eocap
	 * @return
	 * @throws ParseException 
	 */
	@ResponseBody
	@RequestMapping(value = "/meetAnalysis", method = RequestMethod.POST)
	public Object abnormalPhoneAnalysis(ModelMap model,HttpServletResponse response, @RequestBody MeetAnalysisParams maParams) throws ParseException {
		Map<String, Object> result = new HashMap<String, Object>();
		if (StringUtils.isNotEmpty(maParams.getShowType())) {
			List<MeetAnalysis> mas = meetAnalysisService.findMeetPersonInit(maParams);
			/* 嫌疑人手机号码集合 */
			List<String> phones = new ArrayList<>();
			for(String phoneNumber : maParams.getCheckedPhone().split(",")) {
				phones.add(phoneNumber);
			}
			result.put("phones",phones);
			result.put("mas",mas);
		}/*else {
			List<MeetAnalysis> mas = meetAnalysisService.findMeetPersonInit(maParams);
			List<String> callTimes = new ArrayList<String>();
			if(null != mas && !mas.isEmpty()) {
				for(MeetAnalysis ma : mas) {
					callTimes.add(ma.getMeetDate());
				}
			}
			maParams.setCallTimes(callTimes);
			Map<String, String> trackEventsMap =meetAnalysisService.findMeetAnalysisMap(maParams);
			result.put("map",trackEventsMap);
		}*/
		result.put("showType",maParams.getShowType());
		return SUCCESS(result);
	}
	
	/**
     * 相互通话户导出excel
	 * @throws Exception 
     */
    @RequestMapping("/exportMeetAnalysis")
    @ResponseBody
    public void exportCallAnalysis(HttpServletResponse response, MeetAnalysisParams maParams) throws Exception {

        // 生成导出excel名称
        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String fileName = "碰面分析" + dateFormat.format(date);
        
        List<MeetAnalysis> mas = meetAnalysisService.findMeetPersonInit(maParams);
		/* 嫌疑人手机号码集合 */
		List<String> phones = new ArrayList<>();
		/* 嫌疑人手机号码集合 */
		List<String> title = new ArrayList<>();
		title.add("碰面日期");
		title.add("星期");
		for(String phoneNumber : maParams.getCheckedPhone().split(",")) {
			phones.add(phoneNumber);
			title.add(phoneNumber);
		}
		 //设置导出Excel标题
        String[] titles = title.toArray(new String[title.size()]);
        List<Map<Integer, String>> lists = new ArrayList<Map<Integer, String>>();
        if(null != phones && phones.size() > 0) {
        	if(null != mas && !mas.isEmpty()) {
        		int n = 0;
        		int w = 1;
				for(int i = 0 ; i < mas.size() ; i++) {
					Map<Integer, String> map = new HashMap<Integer, String>();
					map.put(n, mas.get(i).getMeetDate());
					map.put(n+1, mas.get(i).getMeetWeek());
					for(int j = 0 ; j < phones.size() ; j++) {
						if(mas.get(i).getMeetPhone().contains(phones.get(j))) {
							map.put(++w, "✔");
						}else {
							map.put(++w, "✖");
						}
						if(j == phones.size() - 1) {
							w = 1;
						}
					}
					n = 0;
					lists.add(map);
				}
			}
        }

		//插入导出日志
        //dataOperationLogService.save(null, super.getLoginUser(), new PhoneRecord(), new PhoneRecord(), SystemFlag.HD, ModuleFlag.EACHOTHER, ActionType.EXPORT);
        // 把导出的内容写入到流里面
        byte[] content = ExcelUtil.writeExcel(titles, lists);
        InputStream is = new ByteArrayInputStream(content);

        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
        }
    }
	
}
